#!/usr/bin/env python

import os, sys, shutil, zipfile
from optparse import OptionParser

op = OptionParser ()
op.add_option ( "-n", "--name", dest = "name", help = "Set the module name (eg. media_manager)", metavar = "NAME" )
op.add_option ( "-c", "--class", dest = "class", help = "Set the class name (eg. MediaManager)", metavar = "CLASS" )
op.add_option ( "-p", "--path", dest = "path", help = "Set the site destination path", metavar = "PATH", default = "." )
op.add_option ( "-l", "--liwe", dest = "liwe", help = "Set the liwe sources directory", metavar = "LIWE" )

( options, args ) = op.parse_args ()

dct = eval ( str ( options ) )

if not dct.get ( "liwe" ):
	sys.stderr.write ( "\nERROR: you MUST specify the --liwe parameter.\n" )
	sys.exit ( 1 )

if not dct.get ( "name" ):
	sys.stderr.write ( "\nERROR: you MUST specify the --name parameter.\n" )
	sys.exit ( 1 )

if not dct.get ( "class" ):
	sys.stderr.write ( "\nERROR: you MUST specify the --class parameter.\n" )
	sys.exit ( 1 )

liwe_module_base = os.path.join ( dct [ 'liwe' ], 'tools', 'data', 'liwe_module_base.zip' )
if not os.path.isfile ( liwe_module_base ):
	sys.stderr.write ( "\nERROR: could not find %s. Maybe the --liwe parameter specified is invalid.\n" % liwe_module_base )
	sys.exit ( 1 )

dest_path = os.path.join ( dct [ 'path' ], dct [ 'name' ] )

os.mkdir ( dest_path )
zfile = zipfile.ZipFile ( liwe_module_base, mode = 'r' )
zfile.extractall ( dest_path )
zfile.close ()

def replace_refs ( full_fname, lowcase, upcase ):
	data = open ( full_fname ).read ()

	data = data.replace ( "_module_name_", lowcase ).replace ( "ModuleName", upcase )

	open ( full_fname, "w" ).write ( data )

def sub_stubs ( arg, dirname, fnames ):
	#print arg, dirname, fnames

	for f in fnames:
		full_fname = os.path.join ( dirname, f )
		if f.startswith ( "_module_name_" ):
			dest_fname = full_fname.replace ( "_module_name_", arg [ 'name' ] )
			os.rename ( full_fname, dest_fname )
			full_fname = dest_fname

		if os.path.isfile ( full_fname ):
			replace_refs ( full_fname, arg [ 'name' ], arg [ 'class' ] )

os.path.walk ( dest_path, sub_stubs, dct )
